package com.blast.comicsisland.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blast.comicsisland.R;
import com.blast.comicsisland.utils.JsonUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ms.square.android.expandabletextview.ExpandableTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 漫画详情页 包含漫画图标 收藏 阅读按钮 点击收藏写入数据库收藏type
 * 点击阅读读取数据库查找观看至哪个章节的哪页
 * 点击书评区跳转至书评区（不作）
 * 点击下方章节条目跳转至章节条目
 */
public class CommicActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView title;
    private SimpleDraweeView icon;
    private ImageView back;
    private TextView comicType;
    private TextView comicAuthor;
    private TextView comicCount;
    private ExpandableTextView description;
    private String urlhead;
    private String urlbody;
    private Button btnBeginRead;
    private String bookId;
    private String sourceName;
    private String bigbookName;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 99:
                    HashMap<String, String> hashMap = (HashMap) msg.obj;
                    if (hashMap != null) {
                        bigbookName = (String) hashMap.get("bigbookName");
                        String bigbookAuthor = (String) hashMap.get("bigbookAuthor");
                        String subjectName = (String) hashMap.get("subjectName");
                        String bigbookBrief = (String) hashMap.get("bigbookBrief");
                        String coverurl = (String) hashMap.get("coverurl");
                        String bigbookview = (String) hashMap.get("bigbookview");
                        bookId = hashMap.get("bookId");
                        sourceName = hashMap.get("sourceName");
                        title.setText(bigbookName);
                        Uri uri = Uri.parse(coverurl);
                        icon.setImageURI(uri);
                        comicAuthor.setText(bigbookAuthor);
                        comicCount.setText(bigbookview);
                        description.setText(bigbookBrief);
                        comicType.setText(subjectName);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commic);
        title = (TextView) findViewById(R.id.commicdetail_item_title_text);
        back = (ImageView) findViewById(R.id.commicdetail_item_back_image);
        back.setOnClickListener(this);
        icon = (SimpleDraweeView) findViewById(R.id.cover_image);
        comicType = (TextView) findViewById(R.id.comic_type);
        comicAuthor = (TextView) findViewById(R.id.comic_author);
        comicCount = (TextView) findViewById(R.id.comic_count);
        description = (ExpandableTextView) findViewById(R.id.expand_text_view);
        btnBeginRead = (Button) findViewById(R.id.begin_read);
        btnBeginRead.setOnClickListener(this);

        String bigBookId = getIntent().getExtras().getString("bigBookId");
        if (bigBookId != null) {
            urlhead = "http://mhjk.1391.com/comic/comicsdetail_v2?e=" + System.currentTimeMillis() / 1000 + "&bigbookid=" + bigBookId + "&channelid=baidu";
            urlbody = "http://mhjk.1391.com/comic/bigbooksource_v3?e=" + System.currentTimeMillis() / 1000 + "&bigbookid=" + bigBookId + "&channelid=baidu ";
            MyThread thread = new MyThread();
            thread.setOSPriority(19);
            thread.start();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.commicdetail_item_back_image:
                finish();
                break;
            case R.id.begin_read:
                Intent intent = new Intent(this, ChapterActivity.class);
                intent.putExtra("bookId", bookId);
                intent.putExtra("sourceName", sourceName);
                intent.putExtra("bigbookName", bigbookName);
                startActivity(intent);
                break;
        }
    }


    class MyThread extends Thread {
        private int mOSPriority = Process.THREAD_PRIORITY_DEFAULT;

        public void setOSPriority(int p) {
            mOSPriority = p;
        }

        @Override
        public void run() {
            Process.setThreadPriority(mOSPriority);
            if (urlhead != null || urlbody != null) {
                HashMap<String, String> maps = null;
                if (urlhead != null && urlbody != null) {
                    String strHead = JsonUtils.doGetRequest(urlhead);
                    String strBody = JsonUtils.doGetRequest(urlbody);
                    maps = new HashMap<>();
                    try {
                        JSONObject headObject = new JSONObject(strHead);
                        JSONObject infoObject = headObject.getJSONObject("info");
                        JSONArray comicsDetailArray = infoObject.getJSONArray("comicsdetail");
                        JSONObject comicsObject = comicsDetailArray.getJSONObject(0);
                        maps.put("bigbookName", comicsObject.getString("bigbook_name"));
                        maps.put("bigbookAuthor", comicsObject.getString("bigbook_author"));
                        maps.put("bigbookId", comicsObject.getString("bigbook_id"));
                        maps.put("subjectName", comicsObject.getString("subject_name"));
                        maps.put("bigbookBrief", comicsObject.getString("bigbook_brief"));
                        maps.put("discusscount", comicsObject.optString("discusscount"));
                        maps.put("gradescore", comicsObject.getString("gradescore"));
                        maps.put("coverurl", comicsObject.getString("coverurl"));
                        maps.put("adgroupid", comicsObject.getString("adgroupid"));
                        maps.put("bigbookview", comicsObject.getString("bigbookview"));
                        maps.put("keyName", comicsObject.getString("key_name"));
                        /*
                        "info": {
                        "comicssource": [ {
                        "book_id": 84702,
                        "totalpart": 154,
                        "updatemessage": "第145集(下)",
                        "updatedate": "2015-06-22",
                        "source_name": "腾讯漫画", "progresstype": 1
                        } ]
                        }
                         */

                        JSONObject bodyObject = new JSONObject(strBody);
                        JSONObject bodyInfoObject = bodyObject.getJSONObject("info");
                        JSONArray comicssourceArr = bodyInfoObject.getJSONArray("comicssource");
                        for (int i = 0; i < comicssourceArr.length(); i++) {
                            JSONObject jsonObject = comicssourceArr.getJSONObject(i);
                            String bookId = jsonObject.getString("book_id");
                            String updateMessage = jsonObject.getString("updatemessage");
                            String updateDate = jsonObject.getString("updatedate");
                            String sourceName = jsonObject.getString("source_name");
                            maps.put("bookId", bookId);
                            maps.put("updateMessage", updateMessage);
                            maps.put("updateDate", updateDate);
                            maps.put("sourceName", sourceName);
                        }
                        Message message = handler.obtainMessage();
                        message.what = 99;
                        message.obj = maps;
                        handler.sendMessage(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            } else {
                Toast.makeText(CommicActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
}
